<template>
  <div class="col-box">
    <div :style="{ width: lastX + 'px' }">Aside宽 {{ lastX }}</div>
    <!-- 给可拖动元素添加鼠标按下事件 -->
    <div class="resize" @mousedown="mouseDown"></div>
    <div>Main</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { throttle } from "lodash-es";
/**拖动改变宽度实现 */
// 拖动改变元素宽度
const lastX = ref(200);
// 鼠标移动事件，将鼠标指针相对于屏幕的 X 轴坐标赋值给需要动态变化的元素宽度
const mouseMove = (event: any) => {
  lastX.value = event.screenX;
};
// 鼠标按下事件
const mouseDown = (event: any) => {
  document.addEventListener("mousemove", mouseMove);
  lastX.value = event.screenX;
};
// 鼠标释放事件
const mouseUp = () => {
  // 指定元素可改变的最大以及最小宽度
  const moveX = lastX.value > 500 ? 500 : lastX.value < 200 ? 200 : lastX.value;
  lastX.value = moveX;
  document.removeEventListener("mousemove", mouseMove);
};
// 鼠标释放节流事件
const handleMoveThrottled = throttle(mouseUp, 300);
// onMounted时添加鼠标移动事件监听器
onMounted(() => {
  document.addEventListener("mouseup", handleMoveThrottled);
});
// 组件卸载时移除监听
onUnmounted(() => {
  document.removeEventListener("mouseup", handleMoveThrottled);
});
</script>

<style lang="scss" scoped>
.col-box {
  display: flex;
  height: 100%;
  .resize {
    width: 10px;
    height: 100%;
    background-color: blue;
  }
}
</style>
